/**
 * 返回base64编码过的二维码图片
 */
package org.free.learn.zxing;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.free.example.zxing.EncoderQRCode;
import org.base64.Base64;

/**
 * User: Administrator
 * Date: 11-8-16
 * Time: 下午11:16
 */
public class OutputQRCodeServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String oInfo = req.getParameter("info");
        if(oInfo != null && !"".equals(oInfo)){
            String info = new String(oInfo.getBytes("GBK") , "GBK");

            ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
            //二维码编码器
            EncoderQRCode encoder = new EncoderQRCode();
            //构造一个300*300的二位码图形，并输出到流
            encoder.encodeByStream(info , 100 , 100 , byteOutStream);

            if(byteOutStream.size() > 0 ){
                //对二维码图形进行base64编码
                String nInfo = Base64.encodeBytes(byteOutStream.toByteArray());
                resp.getWriter().print(nInfo);
            }

        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req , resp);
    }

}
